<template lang="pug">
.styles
  .header
    .header-title
      span 业态管理
      label 支持png、jpg格式图片。最多7张，建议尺寸180*183
    .header-handle
      el-button(name="primary" size="small" @click="save" v-if="$permission('AB-01002-005')") 应用到平台
  .styles-content
    .styles-item(v-for="item, index in styles")
      .styles-item-bg(:style="item.fileUrl | filterUrl")
        .styles-item-del(@click="delStyle(item, index)" v-if="$permission('AB-01002-003')")
          .iconfont.icon-delete
        el-upload(
          action="#"
          :multiple="false"
          accept="image/png, image/jpeg, image/jpg, image/gif"
          ref="styleUpload"
          :show-file-list="false"
          :auto-upload="false"
          list-type="picture"
          :on-change="handleStyleChange"
        )
          .styles-item-btn(slot="trigger" @click="changeStyleFile(item)" v-if="$permission('AB-01002-002')") 更换图片
      .styles-item-bd(v-show="!item.showEdit")
        span {{item.styleName}}
        .iconfont.icon-edit(@click="editName(item, 'style', item.styleId)" v-if="$permission('AB-01002-004')")
      .styles-item-bd(v-show="item.showEdit")
        el-input(v-model="item.styleName", :ref="`input_name_style_${item.styleId}`" @blur="blurInput(item)")
    .styles-item(v-for="item, index in tempFileList")
      .styles-item-bg(:style="item.url | filterUrl")
        .styles-item-del(@click="delTempFile(index)" v-if="$permission('AB-01002-003')")
          .iconfont.icon-delete
        el-upload(
          action="#"
          :multiple="false"
          accept="image/png, image/jpeg, image/jpg, image/gif"
          ref="tempStyleUpload"
          :show-file-list="false"
          :auto-upload="false"
          list-type="picture"
          :file-list="tempFileList"
          :on-change="handleTempStyleChange"
        )
          .styles-item-btn(slot="trigger" @click="changeTempFlie(index)" v-if="$permission('AB-01002-002')") 更换图片
      .styles-item-bd(v-show="!item.showEdit")
        span {{item.styleName}}
        .iconfont.icon-edit(@click="editName(item, 'file', index)" v-if="$permission('AB-01002-004')")
      .styles-item-bd(v-show="item.showEdit")
        el-input(v-model="item.styleName", :ref="`input_name_file_${index}`" @blur="blurInput(item)")
    .styles-item(v-if="$permission('AB-01002-001')")
      el-upload(
        action="#"
        :multiple="false"
        accept="image/png, image/jpeg, image/jpg, image/gif"
        ref="upload"
        :show-file-list="false"
        :auto-upload="false"
        :file-list="tempFileList"
        list-type="picture"
        :on-change="handleChange"
      )
        .file-upload(slot="trigger")
          .iconfont.icon-picture
          .file-upload-info 添加图片
</template>

<script>
import { getStyleList, postUpdateStyle, FileUpload, postAddStyle } from 'api'
let loading = ''
export default {
  name: 'styles',
  data () {
    return {
      styles: [],
      tempFileList: [],
      tempFileIndex: ''
    }
  },
  methods: {
    async fileUpload (raw) {
      return new Promise(async (resolve, reject) => {
        try {
          let formData = new FormData()
          formData.append('Filedata', raw)
          formData.append("applicationId", 4)
          const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
          resolve({ ...ResultSet.Result[0] })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    async save () {
      try {
        loading = this.$loading({
          lock: true,
          text: '保存中....',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let imgs = []
        if (this.tempFileList.length) {
          imgs = await Promise.all(this.tempFileList.map(async (item) => {
            try {
              const file = await this.fileUpload(item.raw)
              return { fileId: file.fileId, styleName: item.styleName, fileUrl: file.fileUrl }
            } catch (err) {
              console.error('error: ' + JSON.stringify(err))
            }
          }))
        }
        imgs.forEach(row => {
          this.styles.push(row)
        })
        await this.$axios.post(postAddStyle, { styleList: this.styles })
        this.init()
        this.tempFileList = []
        setTimeout(() => {
          loading.close()
        }, 1000)
      } catch (err) {
        setTimeout(() => {
          loading.close()
        }, 1000)
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    delStyle (item, index) {
      this.$confirm('是否删除该张照片？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        this.styles.splice(index, 1)
      })
    },
    changeStyleFile (item) {
      this.currentItem = item
    },
    delTempFile (index) {
      this.tempFileList.splice(index, 1)
    },
    changeTempFlie (index) {
      this.tempFileIndex = index
    },
    handleTempStyleChange (file, fileList) {
      let newFile = { ...file, showEdit: true, styleName: this.tempFileList[this.tempFileIndex].styleName }
      this.tempFileList.splice(this.tempFileIndex, 1, newFile)
    },
    async handleStyleChange (file, fileList) {
      try {
        const fileItem = await this.fileUpload(file.raw)
        let index = this.styles.findIndex(item => item.styleId === this.currentItem.styleId)
        this.styles[index].fileUrl = fileItem.fileUrl
        this.styles[index].fileId = fileItem.fileId
        // await this.$axios.post(postUpdateStyle, { styleId: this.currentItem.styleId, styleName: this.currentItem.styleName, fileUrl: fileItem.fileUrl, fileId: fileItem.fileId })
        // this.init()
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
      console.log(file)
    },
    handleChange (file, fileList) {
      if (this.styles.length + this.tempFileList.length >= 7) {
        this.$message.error('业态最多只能上传7张！')
        return
      }
      fileList.forEach(item => {
        if (file.url === item.url) {
          this.$set(item, 'showEdit', true)
          this.$set(item, 'styleName', '')
        }
      })
      this.tempFileList = fileList
    },
    onExceed () {
      this.$message.error('业态管理最多支持传7张图片！')
    },
    editName (item, key, index) {
      item.showEdit = true
      this.$nextTick(() => {
        this.$refs[`input_name_${key}_${index}`][0].focus()
      })
    },
    blurInput (item) {
      item.showEdit = false
    },
    async init () {
      try {
        const { ResultSet } = await this.$axios.post(getStyleList)
        ResultSet.userData.styleList.forEach(item => { item.showEdit = false })
        this.styles = ResultSet.userData.styleList
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.init()
    })
  }
} 
</script>

<style lang="scss">
.banner-upload {
  .el-upload--picture-card {
    width: 100%;
    height: 100%;
    background: transparent;
    border: none !important;
  }
  .header-popover {
    &.el-popover {
      padding: 0 !important;
    }
  }
}
</style>

<style lang="scss" scoped>
.styles {
  background: #fff;
  border-radius: 10px 10px 0 0;
  width: 100%;
  height: 100%;
  padding: 0 40px;
}
.header {
  padding: 16px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #EDEDED;
}
.header-title {
  span {
    display: inline-block;
    font-size: 16px;
    line-height: 24px;
    color: #3E4373;
    margin-right: 16px;
  }
  label {
    font-size: 12px;
    line-height: 20px;
    color: #8B8EAB;
  }
}
.styles-content {
  padding: 24px 0;
  display: flex;
  flex-wrap: wrap;
}
.styles-item {
  position: relative;
  margin-right: 24px;
  margin-bottom: 24px;
  width: 180px;
  background: #F7F7FD;
  border-radius: 6px;
}
.styles-item-bg {
  position: relative;
  width: 100%;
  height: 183px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  border-radius: 6px 6px 0 0;
  &:hover {
    .styles-item-del {
      display: flex;
    }
    .styles-item-btn {
      display: block;
    }
  }
}
.styles-item-bd {
  position: relative;
  width: 100%;
  height: 56px;
  font-size: 16px;
  padding: 8px;
  font-weight: bold;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  &:hover {
    .iconfont {
      display: inline-block;
    }
  }
  .iconfont {
    display: none;
    position: absolute;
    top: 50%;
    left: 65%;
    transform: translateY(-50%);
    font-size: 24px;
    color: #B2B4C7;
    cursor: pointer;
  }
}
.file-upload {
  width: 180px;
  height: 239px;
  border-radius: 6px;
  background: #F7F7FD;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  cursor: pointer;
  .iconfont {
    font-size: 40px;
    color: #B2B4C7;
  }
  .file-upload-info {
     font-size: 16px;
     line-height: 24px;
     color: #B2B4C7;
     margin-top: 8px;
   }
}
.styles-item-del {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 32px;
  height: 32px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 6px;
  display: none;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 24px;
  cursor: pointer;
}
.styles-item-btn {
  display: none;
  width: 96px;
  height: 32px;
  position: absolute;
  left: 8px;
  bottom: 8px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 6px;
  color: #fff;
  font-size: 14px;
  line-height: 32px;
  text-align: center;
  cursor: pointer;
}
</style>
